package org.itli.jnsocket.Service.ServiceImpl;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Mapper.CustomerMapper;
import org.itli.jnsocket.Pojo.Customer;
import org.itli.jnsocket.Service.CustomerService;
import org.itli.jnsocket.Util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    CustomerMapper mapper;
    Gson gson;

    @Autowired
    public void setMapper(CustomerMapper mapper) {
        this.mapper = mapper;
    }

    @Autowired
    public void setGson(Gson gson) {
        this.gson = gson;
    }

    @Override
    public String AllCustomers(PageUtil page) {
        try{
            List<Customer> customers = mapper.AllCustomers(page.getSize(),page.getPage());
            return gson.toJson(customers);
        } catch (Exception e) {
            log.info(e.getLocalizedMessage());
            return "error";
        }
    }

    @Override
    public String AddCustomer(String username, Customer customer) {
        try{
            int i = mapper.AddCustomers(customer, username, username);
            if(i==1){
                return "1";
            }
            else {
                return "0";
            }
        } catch (Exception e) {
            log.info(e.getLocalizedMessage());
            return "error";
        }
    }

    @Override
    public String AlertCustomer(String username, Customer customer) {

        try{
            int i = mapper.UpdateCustomer(customer, username);
            if(i == 1){
                return "1";
            }
            else {
                return "0";
            }
        } catch (Exception e) {
            log.info(e.getLocalizedMessage());
            return "error";
        }
    }

    @Override
    public String DeleteCustomer(String username, Customer customer) {
        try{
            mapper.DeleteCustomer(String.valueOf(customer.getId()));
            return "1";
        } catch (Exception e) {
            log.info(e.getLocalizedMessage());
            return "error";
        }
    }
}
